<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="mainor_form">
          <div class="mainor_te">
            <!-- <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">
                系统自动把当前市场价同步到商户订单（当前配送日期）的配送单价！
              </div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip> -->
            <!-- class="mainor_tea" -->
            <el-button @click="exportMethodDia">导出</el-button>
            <router-link
              :to="{
                path: '/warehouse/now/record',
                query: { time: form.send_time },
              }"
              ><el-button>操作记录</el-button></router-link
            >
          </div>

          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
          >
            <el-form-item label="商品" prop="goods_spu_id">
              <change-goods-input
                ref="changeGoodsInput"
                url="1"
                @clear="
                  () => {
                    this.form.goods_spu_id = '';
                  }
                "
                @sendValue="
                  (data) => {
                    this.form.goods_spu_id = data.id;
                  }
                "
              ></change-goods-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="category_id" class="wid220">
              <el-cascader
                v-model="form.category_id"
                :options="options"
                :props="defaultProps"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="库存预警" prop="warn">
              <el-select
                v-model.trim="form.warn"
                placeholder="库存预警"
                class="wid220"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(item, index) in upper_lower"
                  :key="index"
                  :label="item"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="正负库存" prop="plus_min">
              <el-select
                v-model.trim="form.plus_min"
                placeholder="库存预警"
                class="wid220"
              >
                <el-option label="所有" value="0"></el-option>
                <el-option label="正库存" value="1"></el-option>
                <el-option label="负库存" value="2"></el-option>
              </el-select>
            </el-form-item>
            <div class="clearfix"></div>
            <el-form-item>
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="reset"
                >重置</el-button
              >
              <el-button
                type="primary"
                :loading="listLoading"
                @click="getArticleList"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="main_num boxdq marginTop10">
          <div class="main_num_l box">
            <div class="mainsu_te marginRight5"></div>
            <p>
              库存总金额：
              <em>{{ header_all_money }}</em>
            </p>
          </div>
          <div class="mainsu_te" style="position: relative">
            <el-checkbox
              v-model="display_zero_inventory"
              @change="canceledChange"
              >库存为0不显示</el-checkbox
            >
            <!-- <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">
                勾选后修改商品实时单价并保存，<br />系统会自动同步修改商品的市场价！
              </div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip> -->
          </div>
        </div>
        <div class="main_table marginTop10" style="min-height: 550px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list.data"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            @selection-change="handleSelectionChange"
            :header-cell-class-name="this.$verticaline"
            :summary-method="getSummaries"
            show-summary
          >
            <el-table-column type="selection" />
            <el-table-column label="商品名称" width="150" show-overflow-tooltip>
              <template slot-scope="scope"
                ><span v-if="scope.row.spu_name">
                  {{ scope.row.goods.name }}【{{
                    scope.row.spu_name.title
                  }}】</span
                ></template
              >
            </el-table-column>
            <el-table-column label="SKU编码" prop="goods_spu_code" />
            <el-table-column label="单位" prop="spu_unit.title" />
            <el-table-column
              label="商品分类"
              show-overflow-tooltip
              prop="category_name"
            />
            <el-table-column label="当前库存" prop="inventory.num" />
            <el-table-column
              label="库存均价"
              prop="inventory.price"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <div
                  class="mainus_pe"
                  v-if="scope.row.inventory ? true : false"
                >
                  <div v-if="!scope.row.freight_unit">
                    {{ scope.row.inventory ? scope.row.inventory.price : "" }}
                    <svg
                      aria-hidden="true"
                      class="main_page_svg"
                      width="13"
                      height="13"
                      @click="freighta(scope.$index, 'freight_unit')"
                    >
                      <use xlink:href="#icon-commodity_modify" />
                    </svg>
                  </div>
                  <div v-else class="boxnr">
                    <el-input
                      v-model="scope.row.inventory.price"
                      placeholder="库存单价"
                      class="wid80"
                    ></el-input>
                    <div class="boxnr svg_box">
                      <svg
                        aria-hidden="true"
                        class="main_page_svg marginLeft5"
                        width="20"
                        height="20"
                        @click="
                          inputBlur(
                            scope.row.inventory.price,
                            scope.$index,
                            'freight_unit',
                            'price'
                          )
                        "
                      >
                        <use xlink:href="#icon-index_tick" />
                      </svg>
                      <svg
                        aria-hidden="true"
                        class="main_page_svg marginLeft5"
                        width="12"
                        height="12"
                        @click="
                          (scope.row.inventory.price =
                            scope.row.inventory.price_data),
                            (scope.row.freight_unit = false)
                        "
                      >
                        <use xlink:href="#icon-index_cross" />
                      </svg>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="库存金额" prop="allmoney" />
            <el-table-column
              label="库存上限"
              prop="inventory.upper"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <div
                  class="mainus_pe"
                  v-if="scope.row.inventory ? true : false"
                >
                  <div v-if="!scope.row.freight_upper">
                    {{ scope.row.inventory ? scope.row.inventory.upper : "" }}
                    <svg
                      aria-hidden="true"
                      class="main_page_svg"
                      width="13"
                      height="13"
                      @click="freighta(scope.$index, 'freight_upper')"
                    >
                      <use xlink:href="#icon-commodity_modify" />
                    </svg>
                  </div>
                  <div v-else class="boxnr">
                    <el-input
                      v-model="scope.row.inventory.upper"
                      placeholder="库存上限"
                      class="wid80"
                    ></el-input>
                    <div class="boxnr svg_box">
                      <svg
                        aria-hidden="true"
                        class="main_page_svg marginLeft5"
                        width="20"
                        height="20"
                        @click="
                          inputBlur(
                            scope.row.inventory.upper,
                            scope.$index,
                            'freight_upper',
                            'upper'
                          )
                        "
                      >
                        <use xlink:href="#icon-index_tick" />
                      </svg>
                      <svg
                        aria-hidden="true"
                        class="main_page_svg marginLeft5"
                        width="12"
                        height="12"
                        @click="
                          (scope.row.inventory.upper =
                            scope.row.inventory.upper_data),
                            (scope.row.freight_upper = false)
                        "
                      >
                        <use xlink:href="#icon-index_cross" />
                      </svg>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="库存下限"
              prop="inventory.lower"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <div
                  class="mainus_pe"
                  v-if="scope.row.inventory ? true : false"
                >
                  <div v-if="!scope.row.freight_lower">
                    {{ scope.row.inventory ? scope.row.inventory.lower : "" }}
                    <svg
                      aria-hidden="true"
                      class="main_page_svg"
                      width="13"
                      height="13"
                      @click="freighta(scope.$index, 'freight_lower')"
                    >
                      <use xlink:href="#icon-commodity_modify" />
                    </svg>
                  </div>
                  <div v-else class="boxnr">
                    <el-input
                      v-model="scope.row.inventory.lower"
                      placeholder="库存下限"
                      class="wid80"
                    ></el-input>
                    <div class="boxnr svg_box">
                      <svg
                        aria-hidden="true"
                        class="main_page_svg marginLeft5"
                        width="20"
                        height="20"
                        @click="
                          inputBlur(
                            scope.row.inventory.lower,
                            scope.$index,
                            'freight_lower',
                            'lower'
                          )
                        "
                      >
                        <use xlink:href="#icon-index_tick" />
                      </svg>
                      <svg
                        aria-hidden="true"
                        class="main_page_svg marginLeft5"
                        width="12"
                        height="12"
                        @click="
                          (scope.row.inventory.lower =
                            scope.row.inventory.lower_data),
                            (scope.row.freight_lower = false)
                        "
                      >
                        <use xlink:href="#icon-index_cross" />
                      </svg>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <el-pagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
      <el-dialog
        title="导出"
        :visible.sync="exportFormVisible"
        class="main_dialog dialog500"
        @close="type = list.field"
      >
        <div class="export">你选择了{{ this.selectArr.length }}条数据</div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="exportFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="exportConfim" v-repeatClick
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  storage_index,
  storage_update,
  export_storage_now,
} from "@/api/warehouse/warehouseNow";
import { setting_company } from "@/api/currency";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime, recursion, category, exportMethod } from "@/utils/index";

export default {
  directives: {
    // 聚焦元素
    focus: {
      inserted(el) {
        el.querySelector("input").focus();
      },
    },
  },
  computed: {
    ...mapGetters(["avatar"]),
    reverseSum() {
      return this.percent_list.reverse();
    },
  },

  components: {},
  data() {
    return {
      exportMethod,
      // 列表数据
      list: {
        list: {
          data: [],
        },
      },
      listLoading: false,
      // 搜索
      form: {
        pid: "",
        category_id: [],
        goods_spu_id: "",
        warn: "",
        plus_min: "", //正负库存
      },
      // 库存为o不显示
      display_zero_inventory: false,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      offsetParent: true,
      // 批量同步
      percent_gs: 0,
      percent: 0,
      percent_list: [],
      addedFormVisible: false,
      // 全选
      selectArr: [],
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      header_all_money: 0,
      list_money: 0,
      // 库存预警
      upper_lower: {},
      // 焦点
      offsetParent: true,
      exportFormVisible: false,
    };
  },
  mounted() {
    window.Echo.channel(
      "batchDispatchPricing." + this.avatar.company_id
    ).listen("BatchDispatchPricingEvent", (e) => {
      this.percent_gs = parseInt(this.percent_gs) + 1;
      if ((this.percent_gs / this.selectArr.length) * 100 >= 100) {
        this.percent = 100;
        return;
      }
      this.percent =
        this.percent_gs / this.selectArr.length
          ? parseInt((this.percent_gs / this.selectArr.length) * 100)
          : 0;
      if (e.notice.msg == "ok") {
        this.percent_list.push({
          num: this.percent,
          type: 1,
          order_id: e.notice.goods_spu_id,
        });
      } else {
        this.percent_list.push({
          num: this.percent,
          type: 2,
          order_id: e.notice.goods_spu_id,
        });
      }
    });
  },
  created() {
    this.storage_index();
  },
  methods: {
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push(item.id);
      });
    },
    exportMethodDia() {
      if (this.selectArr.length > 0) {
        this.exportFormVisible = true;
      } else {
        this.exportConfim();
        // this.$message.error("你还未选择导出的数据");
      }
    },
    // 导出确认
    exportConfim() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      form.ids = this.selectArr.join("-");
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, form)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      export_storage_now(data).then((res) => {
        this.exportMethod(res, "当前库存");
      });
      this.exportFormVisible = false;
    },
    // 库存为0b=不显示
    canceledChange(val) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                display_zero_inventory: val ? 1 : 0,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { display_zero_inventory: val ? 1 : 0 }
      );
      setting_company(data).then((res) => {
        if (res.errcode == 0) {
          this.storage_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.storage_index();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.$refs["changeGoodsInput"].name = "";
      this.storage_index();
    },
    storage_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.current,
        this.list_form()
      );
      storage_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.display_zero_inventory =
            res.data.display_zero_inventory == 1 ? true : false;
          this.options = recursion(res.data.categoryList, true);
          let category = res.data.category;
          this.header_all_money = res.data.money;
          let list_money = 0;
          res.data.list.data.map((e) => {
            if (e.inventory) {
              e.inventory.price_data = e.inventory.price;
              e.inventory.upper_data = e.inventory.upper;
              e.inventory.lower_data = e.inventory.lower;
            }
            e.show = false;
            e.freight_unit = false;
            e.freight_upper = false;
            e.freight_lower = false;
            if (e.inventory && e.inventory.price) {
              e.allmoney = this.$toFixed(
                parseFloat(e.inventory.num) * parseFloat(e.inventory.price)
              );
            }

            if (e.allmoney == undefined || e.allmoney == "") {
            } else {
              list_money += Number(e.allmoney);
            }

            e.category_name = "";
            let title = [];
            if (category[e.goods.pid]) {
              title.push(category[e.goods.pid].title);
              if (
                category[e.goods.pid].selfNext &&
                category[e.goods.pid].selfNext[e.goods.category_id]
              ) {
                title.push(
                  category[e.goods.pid].selfNext[e.goods.category_id].title
                );
              }
            }
            e.category_name = title.join("|");
          });
          this.list_money = this.$toFixed(Number(list_money));
          this.list = res.data;
          this.upper_lower = res.data.upper_lower;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },

    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      return form;
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.storage_index();
    },
    changePage(page) {
      this.current.page = page;
      this.storage_index();
    },

    // 点击排序
    freighta(index, name) {
      if (this.offsetParent) {
        this.list.list.data[index][name] = !this.list.list.data[index][name];
      }
    },
    inputBlur(val, index, name, type) {
      this.offsetParent = false;
      if (/^(\d+\.?)?\d{0,2}$/.test(parseFloat(val)) && val != "") {
        this.list.list.data[index][name] = !this.list.list.data[index][name];
        this.offsetParent = true;
        this.storage_update(val, this.list.list.data[index].inventory.id, type);
      }
    },
    storage_update(val, id, type) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { id: id, field: type, value: val })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id, field: type, value: val }
      );
      storage_update(data).then((res) => {
        if (res.errcode == 0) {
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 表单合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        switch (index) {
          case 1:
            sums[index] = "合计";
            break;
          case 7:
            sums[index] = this.list_money;
        }
      });

      return sums;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 180px);
  }

  .main_dialog {
    .progress_list {
      margin-top: 10px;
      p {
        height: 24px;
        line-height: 24px;
      }
      .progress_list_red {
        color: red;
      }
      .progress_list_su {
        color: #03a98e;
      }
    }
  }
}
.export {
  text-align: center;
  font-size: 18px;
  margin-top: 20px;
}

// 对错 svg展示
.svg_box {
  display: flex;
  flex-direction: column;
}
</style>
